#ifndef HTTPDOWNLOAD_H
#define HTTPDOWNLOAD_H

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QFile>


class HTTPDownload : public QNetworkAccessManager
{
    Q_OBJECT

signals:
    void s_finished(QNetworkReply *reply);  //下载完成

public:
    explicit HTTPDownload(QObject *parent = nullptr);
    virtual ~HTTPDownload();

public:
    //下载url，保存到localpath(包含文件名，缺省则根据url的路径来保存到相对本程序的位置)
    //writeToFile为false,则不保存为文件，保存至httpData。
    bool download(QUrl url, QString localpath = "", bool writeToFile = true);
    //停止下载，还没写完
    void stop();

protected:
    bool checkURL(QUrl url);


private slots:
    //注意，一下几个函数不一定按顺序触发，比如有可能先finished,再readyRead!!!
    void onReadyRead(); //有数据到来，要保存
    void onDownloadProgress(qint64 a,qint64 b); //下载进度
    void onFinished(QNetworkReply *reply);  //完成下载，reply用于接收消息
    void onReplyError(QNetworkReply::NetworkError e);   //下载错误



//数据成员

public:
    QByteArray m_baHttpData;    //下载保存的数据

private:
    int m_nWriteType;   //0:写入QByteArray(httpData),缺省;1:写入文件

    QString m_strLocalFilePathName;   //存放的本地文件路径和名称
    QFile m_fileOut;     //数据要写入的文件

    QNetworkReply *m_pNetWorkReply;
    QNetworkRequest m_NetWorkRequest;

    bool m_bHttpRequestAbort;  //防止用户多次调用m_pNetWorkReply->abort()


    //QNetworkAccessManager *m_netAccessManager;//网络参数
    //QNetworkReply *m_netReply;

    //QUrl m_urlAdress;//网络地址
    //QString m_strFileName;//需要下载的文件名
    //QString m_strDir;//文件的存储位置

    //QFile *m_file;//下载的文件
    //qint64 m_nReceived;//下载文件时，已经接收的文件大小和总共大小
    //qint64 m_nTotal;

};

#endif
